package com.duke.shaking.more;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.duke.shaking.BaseActivity;
import com.duke.shaking.R;
import com.duke.shaking.pojo.Order;
import com.duke.shaking.utils.pay.ProductDetail;
import com.duke.shaking.utils.pay.Products;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class OrderAdapter extends BaseAdapter {
	
	private LayoutInflater inflater;
	private List<Order> orders;
	private Context context;
	public OrderAdapter(Context context) {
		this.context = context;
		inflater = LayoutInflater.from(context); 
	}
	
	public void setDataSource(List<Order> orders) {
		this.orders = orders;
	}
	
	public int getCount() {
		if (orders == null) {
			return 0;
		}
		return orders.size();
	}

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		if (orders == null || position >= orders.size()) {
			return null;
		}
		return orders.get(position);
	}

	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		if (orders == null || position >= orders.size()) {
			return null;
		}
		
		Order order = orders.get(position);
		if (order == null) {
			return null;
		}
		ProductDetail pd = Products.getProductDetail(order.getProdectType());
		if (pd == null) {
			return null;
		}
		ViewHolder viewHolder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.view_order_item, null);
			viewHolder = new ViewHolder();
			viewHolder.txtOrderTime = (TextView)convertView.findViewById(R.id.txt_order_time);
			viewHolder.txtState = (TextView)convertView.findViewById(R.id.txt_state);
			viewHolder.txtNum = (TextView)convertView.findViewById(R.id.txt_num);
			convertView.setTag(viewHolder);
		}
		else {
			viewHolder = (ViewHolder)convertView.getTag();
		}
		
		Date t = order.getOrderTime();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm",
				Locale.CHINA);
		viewHolder.txtOrderTime.setText(formatter.format(t));
		
		viewHolder.txtNum.setText(String.valueOf(pd.coins));
		if (order.getOrderState() == Order.ORDER_STATE_UNFIN) {
			viewHolder.txtState.setText(R.string.order_state_query);
		}
		else if (order.getOrderState() == Order.ORDER_STATE_DONE) {
			viewHolder.txtState.setText(R.string.order_state_successful);
		}
		else if (order.getOrderState() == Order.ORDER_STATE_QUERY_FAILED) {
			viewHolder.txtState.setText(R.string.order_state_query_failed);
		}
		else {
			viewHolder.txtState.setText(R.string.order_state_failed);
		}
		
		return convertView;
	}
	
	private class ViewHolder {
		public TextView txtOrderTime;
		public TextView txtState;
		public TextView txtNum;
	}

}
